using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.GamePlay.Data;
using NetProtocol.Client;
using UnityEngine.UI;

namespace IQIGame.Onigao.GamePlay
{
    public class UISubmitItem : UIEntityWindow
    {
        public enum SubmitFailReason
        {
            WrongCombination,
            NotEnough,
        }

        /// <summary>
        /// 静态配置
        /// </summary>
        private static UICreateConfig _createConfig = new()
        {
            prefabName = nameof(UISubmitItem),
            layer = EUILayer.Normal,
        };

        /// <summary>
        /// 创建UI的配置
        /// </summary>
        public override IUICreateConfig createConfig => _createConfig;

        #region Template Generate,don't modify

        protected class UIB_UISubmitItem
        {
            #region ObjectBinding Generate

            public ExText text { protected set; get; }
            public ExButton btnCancel { protected set; get; }
            public ExButton btnConfirm { protected set; get; }
            public ExLoopVerticalScrollRect loopVerticalScrollRect { protected set; get; }
            public ExLoopHorizontalScrollRect loopHorizontalScrollRect { protected set; get; }
            public ExButton btnClose { protected set; get; }

            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<ExText>("text", out var __tbv0);
                text = __tbv0;
                __binding.TryGetVariableValue<ExButton>("btnCancel", out var __tbv1);
                btnCancel = __tbv1;
                __binding.TryGetVariableValue<ExButton>("btnConfirm", out var __tbv2);
                btnConfirm = __tbv2;
                __binding.TryGetVariableValue<ExLoopVerticalScrollRect>("loopVerticalScrollRect", out var __tbv3);
                loopVerticalScrollRect = __tbv3;
                __binding.TryGetVariableValue<ExLoopHorizontalScrollRect>("loopHorizontalScrollRect", out var __tbv4);
                loopHorizontalScrollRect = __tbv4;
                __binding.TryGetVariableValue<ExButton>("btnClose", out var __tbv5);
                btnClose = __tbv5;
            }

            #endregion ObjectBinding Generate
        }

        #endregion Template Generate,don't modify


        protected UIB_UISubmitItem ui { get; set; }

        protected override void BeforeInit()
        {
            ui = new UIB_UISubmitItem();
            ui.InitBinding(csObjBind);
        }

        protected override void OnInit()
        {
            _allowItemCells = InitLoopScroll<UIN_AllowItemCell>(ui.loopVerticalScrollRect, RefreshAllowItemCell);
            _allowItemCells.InitUnitSelected(UnitSelectType.ByExButton, OnAllowItemSelected, OnAllowItemUnSelected);
            _submitItemCells = InitLoopScroll<UIN_SubmitItemCell>(ui.loopHorizontalScrollRect, RefreshSubmitItemCell);
            _submitItemCells.InitUnitSelected(UnitSelectType.ByExButton, OnSubmitItemClicked);

            ui.btnConfirm.onClick.AddListener(OnBtnConfirmClick);
            ui.btnCancel.onClick.AddListener(OnBtnCancelClick);
            ui.btnClose.onClick.AddListener(OnBtnCancelClick);
        }

        protected override void OnShow()
        {

        }

        protected override void OnHide()
        {

        }

        private void OnAllowItemSelected(int index, UIN_AllowItemCell targetAllowItem)
        {
            if (index == -1)
                return;
            var targetIndex = _data.FindIndex(submitItemData => submitItemData == null);
            var submitItemData = _data.levelSubmit.sortedItems[index];
            _data.AddItem(targetIndex, submitItemData);
            targetAllowItem.Selected = true;
            this.RefreshComitList(targetIndex);
        }

        private void OnAllowItemUnSelected(int index, UIN_AllowItemCell targetAllowItem)
        {
            var submitItemData = _data.levelSubmit.sortedItems[index];
            var targetIndex = _data.FindIndex(itemData => itemData?.uniqueId == submitItemData.uniqueId);
            //未找到对应的submitItemData数据，不能移除
            if (targetIndex == -1)
            {
                return;
            }
            _data.RemoveItem(targetIndex);
            targetAllowItem.Selected = false;
            this.RefreshComitList(targetIndex);
        }

        private void RefreshComitList(int targetIndex)
        {
            var submitItemCell = _submitItemCells.GetTEntity(targetIndex);
            submitItemCell?.RefreshCell(targetIndex, _data.curSelectingItems[targetIndex], _data.levelSubmit.ordered);
        }

        private void OnSubmitItemClicked(int index, UIN_SubmitItemCell submitItem)
        {
            var selectingItem = _data.curSelectingItems[index];
            if (selectingItem == null)
            {
                return;
            }
            var allowItems = _data.levelSubmit.sortedItems;
            for (var i = 0; i < allowItems.Count; i++)
            {
                if (allowItems[i].uniqueId == selectingItem.uniqueId)
                {
                    _allowItemCells.UnSelected(i);
                    break;
                }
            }
        }

        protected override void OnShow(UIBaseData data)
        {
            if (data is not UD_SubmitItem submitItemData)
            {
                Hide();
                return;
            }

            _data = submitItemData;
            _allowItemCells.SetUnitMitiSelect(_data.levelSubmit.slotCnt);
            _allowItemCells.RefillCells(_data.levelSubmit.sortedItems.Count);
            _submitItemCells.RefillCells(_data.levelSubmit.slotCnt);
            ui.text.text = submitItemData.levelSubmit.submitDesc;
        }

        private void RefreshAllowItemCell(UIN_AllowItemCell item, int index)
        {
            item.RefreshCell(_data.levelSubmit.sortedItems[index], _data.curSelectingItems);
        }

        private void RefreshSubmitItemCell(UIN_SubmitItemCell item, int index)
        {
            var submitItemData = _data.curSelectingItems[index];
            item.RefreshCell(index, submitItemData, _data.levelSubmit.ordered);
        }

        private async void OnBtnConfirmClick()
        {
            var list = ListPool<long>.Get();
            for (var i = 0; i < _data.curSelectingItems.Count; i++)
            {
                var submitItemData = _data.curSelectingItems[i];

                if (submitItemData is not { canSubmit: true })
                {
                    OnLocalSubmitFail();
                    ListPool<long>.Put(list);
                    return;
                }

                list.Add(_data.curSelectingItems[i].uniqueId);
            }

            var result = await CLevelLogicModule.NetCore.CS_ConfirmItemSubmit(list);
            ListPool<long>.Put(list);
            OnRemoteSubmitResult(result);
        }

        /// <summary>
        /// 本地校验提交组合失败
        /// </summary>
        private void OnLocalSubmitFail()
        {
            _data.ClearItems();
            _submitItemCells.RefreshCells();
            _allowItemCells.RefreshCells();

            var cid = APIUIConst.GetSubmitFailReason(SubmitFailReason.NotEnough);
            NoticeModule.ShowNoticeNoCall(cid);
        }

        /// <summary>
        /// 处理服务器返回的提交结果
        /// </summary>
        /// <param name="result">提交结果</param>
        private void OnRemoteSubmitResult(CNetLevelLogic.ConfirmItemSubmitResultData result)
        {
            Close();
            if (!result.isSuccess)
            {
                var cid = APIUIConst.GetSubmitFailReason(SubmitFailReason.WrongCombination);
                NoticeModule.ShowNoticeNoCall(cid);
            }
        }

        private void OnBtnCancelClick()
        {
            CLevelLogicModule.NetCore.CS_ConfirmItemSubmit(null);
            Close();
        }

        protected override void OnDispose()
        {
            _allowItemCells.Clear();
            _submitItemCells.Clear();
        }

        private LoopScrollAdapter<UIN_AllowItemCell> _allowItemCells;
        private LoopScrollAdapter<UIN_SubmitItemCell> _submitItemCells;

        private UD_SubmitItem _data;
    }
}
